import React from 'react';
import { Button, Empty, List, Typography, Card, Tooltip, Badge, Space } from 'antd';
import { PlusOutlined, DeleteOutlined, MessageOutlined, WifiOutlined, DisconnectOutlined } from '@ant-design/icons';
import { Conversation } from '../../KimiChat';
import './HistoryList.scss';

interface HistoryListProps {
    conversations: Conversation[];
    currentConversationId: string | null;
    onCreateConversation: () => void;
    onDeleteConversation: (conversationId: string) => void;
    onSelectConversation: (conversationId: string) => void;
    isConnected: boolean;
    connectionError: string | null;
}

const HistoryList: React.FC<HistoryListProps> = ({
    conversations,
    currentConversationId,
    onCreateConversation,
    onDeleteConversation,
    onSelectConversation,
    isConnected,
    connectionError
}) => {
    const formatDate = (date: Date) => {
        const now = new Date();
        const diff = now.getTime() - date.getTime();
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            return '今天';
        } else if (days === 1) {
            return '昨天';
        } else if (days < 7) {
            return `${days}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    };

    const getConversationPreview = (conversation: Conversation) => {
        const lastMessage = conversation.messages[conversation.messages.length - 1];
        if (!lastMessage) {
            return '暂无消息';
        }
        return lastMessage.content.length > 30 
            ? lastMessage.content.substring(0, 30) + '...'
            : lastMessage.content;
    };

    const getMessageCount = (conversation: Conversation) => {
        return conversation.messages.length;
    };

    const getPendingAuditCount = (conversation: Conversation) => {
        return conversation.messages.filter(msg => 
            msg.messageType === 'audit' && msg.status === 'pending'
        ).length;
    };

    return (
        <div className="history-list">
            {/* 连接状态指示器 */}
            <div className="history-list__status">
                <Space>
                    {isConnected ? (
                        <Badge status="success" text="已连接" />
                    ) : (
                        <Badge status="error" text="未连接" />
                    )}
                    {isConnected ? (
                        <WifiOutlined className="history-list__status-icon history-list__status-icon--connected" />
                    ) : (
                        <DisconnectOutlined className="history-list__status-icon history-list__status-icon--disconnected" />
                    )}
                </Space>
                {connectionError && (
                    <div className="history-list__error">
                        <Typography.Text type="danger" className="history-list__error-text">
                            {connectionError}
                        </Typography.Text>
                    </div>
                )}
            </div>

            {/* 新建对话按钮 */}
            <div className="history-list__header">
                <Button 
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={onCreateConversation}
                    className="history-list__new-btn"
                    block
                    size="large"
                >
                    新建对话
                </Button>
            </div>
            
            {/* 对话列表 */}
            <div className="history-list__content">
                {conversations.length === 0 ? (
                    <div className="history-list__empty">
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={
                                <>
                                    <Typography.Text strong>暂无对话历史</Typography.Text>
                                    <br />
                                    <Typography.Text type="secondary" className="history-list__empty-tip">
                                        点击上方按钮开始新对话
                                    </Typography.Text>
                                </>
                            }
                        />
                    </div>
                ) : (
                    <List
                        className="history-list__conversations"
                        itemLayout="vertical"
                        dataSource={conversations}
                        renderItem={conversation => {
                            const messageCount = getMessageCount(conversation);
                            const pendingCount = getPendingAuditCount(conversation);
                            const isActive = currentConversationId === conversation.id;
                            
                            return (
                                <List.Item 
                                    key={conversation.id}
                                    className={`history-list__conversation ${
                                        isActive ? 'history-list__conversation--active' : ''
                                    }`}
                                    onClick={() => onSelectConversation(conversation.id)}
                                >
                                    <Card 
                                        className="history-list__conversation-card"
                                        bodyStyle={{ padding: '12px 16px' }}
                                        hoverable
                                        actions={[
                                            <Tooltip title="删除对话" key="delete">
                                                <Button
                                                    type="text"
                                                    danger
                                                    icon={<DeleteOutlined />}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        onDeleteConversation(conversation.id);
                                                    }}
                                                    className="history-list__delete-btn"
                                                />
                                            </Tooltip>
                                        ]}
                                    >
                                        <div className="history-list__conversation-header">
                                            <Typography.Text 
                                                strong 
                                                className="history-list__conversation-title"
                                                ellipsis={{ tooltip: conversation.title }}
                                            >
                                                {conversation.title}
                                            </Typography.Text>
                                            <div className="history-list__conversation-badges">
                                                {messageCount > 0 && (
                                                    <Badge 
                                                        count={messageCount} 
                                                        size="small"
                                                        className="history-list__message-count"
                                                        showZero
                                                    />
                                                )}
                                                {pendingCount > 0 && (
                                                    <Badge 
                                                        count={pendingCount} 
                                                        size="small"
                                                        className="history-list__pending-count"
                                                        style={{ backgroundColor: '#ff4d4f' }}
                                                    />
                                                )}
                                            </div>
                                        </div>
                                        
                                        <div className="history-list__conversation-preview">
                                            <Typography.Text 
                                                type="secondary" 
                                                className="history-list__preview-text"
                                            >
                                                <MessageOutlined className="history-list__preview-icon" />
                                                {getConversationPreview(conversation)}
                                            </Typography.Text>
                                        </div>
                                        
                                        <div className="history-list__conversation-meta">
                                            <Typography.Text 
                                                type="secondary" 
                                                className="history-list__date"
                                            >
                                                {formatDate(conversation.updatedAt)}
                                            </Typography.Text>
                                            {conversation.tableData.length > 0 && (
                                                <Typography.Text 
                                                    type="secondary" 
                                                    className="history-list__table-count"
                                                >
                                                    数据: {conversation.tableData.length}
                                                </Typography.Text>
                                            )}
                                        </div>
                                    </Card>
                                </List.Item>
                            );
                        }}
                    />
                )}
            </div>
        </div>
    );
};

export default HistoryList;